export type ReplaceUrl = (newUrl: string, baseUrl: string, url: string) => string

/**
 * 最后在url返回的时候可以自行进行处理
 * @param call
 */
export function rewriteReplaceUrl(call: ReplaceUrl) {
  replaceUrl = call
}


let replaceUrl: ReplaceUrl = (newUrl, baseUrl, url) => {
  return newUrl
}


export function pathJoin(baseUrl: string, url: string): string {
  let oldUrl = url
  if (url.startsWith('~')) { // 表示绝对路径
    url = url.substring(1)
    return replaceUrl(url, baseUrl, oldUrl)
  }
  let strings = baseUrl.split('/');
  if (url.startsWith('./')) {
    url = url.substring(2)
  }
  strings[strings.length - 1] = url
  url = strings.join('/')
  // 替换..问题
  // "./vue/ContenBtn/../../img/rice.png" 解析不正确 './vue/img/rice.png' './img/rice.png'
  // ./../vue/../img/图层 700 拷贝.png 解析不正确
  strings = url.split('/');
  for (let i = 0; i < strings.length; i++) {
    const item = strings[i]
    if (item === '..') { // 如果匹配到这个，把上一个也一起删除 上一个就是最近的没有删除的
      if (i > 0) {
        for (let j = i - 1; j > 0; j--) {
          if (strings[j] && strings[j] !== '.') {
            strings[i] = ''
            strings[j] = ''
            break
          }
        }
      }
    }
  }
  url = strings.filter(i => i).join('/')
  url = '/' + url
  return replaceUrl(url, baseUrl, oldUrl)
}

// 扩展
export const extensions = ['.js']

export function addExtensions(ext: string) {
  if (ext) {
    extensions.push(ext)
  }
}

/**
 * 判断url是否有扩展
 * @param url
 */
export function urlHasExtension(url: string) {
  // 先获取最后一个/或者\
  let lastIndex = url.lastIndexOf('/')
  let lastIndex2 = url.lastIndexOf('\\')
  if (lastIndex < lastIndex2) {
    lastIndex = lastIndex2
  }
  // 在获取.的位置
  let lastIndexPoint = url.lastIndexOf('.')
  if (lastIndexPoint > -1) {
    // 如果存在点
    // 如果点的位置在分割线之后就认为有扩展
    if (lastIndexPoint > lastIndex) {
      return true
    }
  }
  return false
}

export function noExtensionToAdd(url: string, index: number = 0): string {
  const hasExtension = urlHasExtension(url);
  if (hasExtension) {
    url = url.split('.')[0]
  }
  if (index >= extensions.length) {
    return url
  }
  let last = url.lastIndexOf('?')
  if (last > -1) {
    let splits = url.split('?')
    return splits[0] + extensions[index] + '?' + splits[1]
  }
  return url + extensions[index]
}


// const scripts = document.getElementsByTagName("script"), script = scripts[scripts.length - 1];
// strJsPath=document.querySelector?script.src:script.getAttribute("src",4)//IE8直接.src













